<template>
  <div>
    <!-- 数据表格 -->
    <el-table
      class="elTable"
      ref="myTable"
      v-loading="loading"
      :default-expand-all="defaultExpandAll"
      :highlight-current-row="highlightCurrentRow"
      @current-change="clickCurrentChange"
      :data="tableData"
      @row-click="handleRowClick"
      @select="handleSelect"
      @select-all="handleSelectAll"
      :size="size"
      :width="width"
      :height="height"
      :show-summary="showSummary"
      :summary-method="summaryMethod"
      :max-height="maxHeight"
      :fit="fit"
      :span-method="spanMethod"
      :stripe="stripe"
      :tree-props="treeProps"
      :default-sort="defaultSort"
      :lazy="lazy"
      :load="load"
      :row-class-name="RowClassName"
      :row-key="rowKey"
      :border="border"
    >
      <table-Column
        v-for="(columnInfo, index) in columnConfigs"
        :key="index"
        :column="columnInfo"
      >
        <!-- 操作列中 处理筛选事件 -->
        <icon
          v-if="columnInfo.ScopeTemplate"
          class="el-icon-s-operation"
          @click="columnInfo._click"
        ></icon>
      </table-Column>
    </el-table>

    <!-- 分页 -->
    <el-pagination
      v-if="pageData.TotalCount > 0"
      style="margin: 8px; float: right; margin-top: 18px"
      :page-sizes="pageData.PageSizeSource"
      @size-change="handleSizeChange"
      :current-page="pageData.CurrentPage"
      @current-change="handleCurrentChange"
      :page-size="pageData.PageSize"
      background
      layout="total,sizes,prev,pager,next,jumper"
      :total="pageData.TotalCount"
    >
    </el-pagination>
  </div>
</template>

<script>
import tableColumn from "./column";
export default {
  components: {
    "table-Column": tableColumn,
  },
  model: {
    // 使用model， 这儿2个属性，prop属性说，我要将msg作为该组件被使用时（此处为aa组件被父组件调用）v-model能取到的值，event说，我emit ‘cc’ 的时候，参数的值就是父组件v-model收到的值。
    prop: "value",
    event: "selectData",
  },
  props: {
    // 分页
    Page: {
      type: Boolean,
      default: true,
    },

    columnConfigs: {
      type: Array,
      required: true,
    },
    viewData: {
      type: [Object, Array],
      required: true,
    },
    treeProps: {
      type: Object,
    },
    highlightCurrentRow: Boolean,
    defaultExpandAll: Boolean,

    RowClassName: Function,

    // 树形表格必备条件
    lazy: Boolean,
    load: Function,
    rowKey: String,

    spanMethod: Function,
    summaryMethod: Function,
    defaultSort: Object,

    // element-ui组件属性
    size: String,
    width: [String, Number],
    height: [String, Number],
    maxHeight: {
      type: [String, Number],
      default: document.body.offsetHeight - 250,
    },
    fit: {
      type: Boolean,
      default: true,
    },
    stripe: {
      type: Boolean,
      default: true,
    },
    // 是否开启行点击时间 默认开启
    isRowClick: {
      type: Boolean,
      default: true,
    },
    border: {
      type: Boolean,
      default: true,
    },
    // 启用行选择
    rowSelectable: {
      type: Boolean,
      default: true,
    },

    showSummary: Boolean,

    // 便于双向绑定v-model
    value: Array,
    loading:  {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      tableData: [],
      pageData: new this.$core.Class.PageData(),
      // 选中的数组
      listSelectedData: [],
      // loading: false,
    };
  },
  created() {
    // this.loading = true;
    // 默认要分页
    this.pageData.NotPage = true;
  },
  mounted() {
    // setTimeout(() => {
    //   if (this.loading) {
    //     this.$msg.warning("服务器繁忙，数据可能跑调了。。。");
    //     this.loading = false;
    //   }
    // }, 15000);
  },
  activated() {
    this.$emit("search");
  },
  computed: {
    // 当前列配置的复选项字段名称
    selectionProp() {
      let prop = null;

      this.columnConfigs.forEach((column) => {
        if (column.type == "selection") {
          prop = column.prop;
        }
      });

      return prop;
    },
  },
  methods: {
    search() {
      this.$emit("search");
    },
    // 分页条数改变
    handleSizeChange(val) {
      this.pageData.PageSize = val;
      this.search();
    },
    // 分页数变化
    handleCurrentChange(val) {
      this.pageData.CurrentPage = val;
      this.search();
    },
    // 当表格的当前行发生变化的时候会触发该事件
    clickCurrentChange(currentRow, oldCurrentRow) {
      if (this.enableSingleCheck) {
        // this.$refs.myTable.toggleRowSelection(currentRow)
      }

      this.$emit("current-change", {
        currentRow,
      });
    },
    // 行点击事件
    handleRowClick(row, column, event) {
      if (this.isRowClick) {
        if (this.rowSelectable) {
          this.$refs.myTable.toggleRowSelection(row);

          this.saveSelection({
            row,
          });
        }
      }
      //返回触发点击事件
      this.$emit("row-click", row, column, event);
    },
    // 当用户手动勾选数据行的 Checkbox 时触发的事件
    handleSelect(selection, row) {
      this.saveSelection({
        row,
      });

      this.$emit("select", {
        selection,
        row,
      });
    },
    // 当用户手动勾选全选 Checkbox 时触发的事件
    handleSelectAll(selection) {
      this.saveSelection({
        selection,
      });
    },
    saveSelection({ selection, row }) {
      // 点击复选框/点击行
      if (row) {
        let selectionData = this.listSelectedData.indexOf(row);
        if (selectionData >= 0) {
          this.listSelectedData.remove(row);
        } else {
          this.listSelectedData.push(row);
        }
      }

      // 点击全选的时候
      if (selection) {
        // 全选中
        if (selection.length > 0) {
          this.tableData.forEach((tableRow) => {
            // 是否存在已选择数据中
            let selectKey = this.listSelectedData.indexOf(tableRow);
            // 不存在已选中
            if (selectKey == -1) {
              // 数据存在全选中
              if (selection.indexOf(tableRow) >= 0) {
                this.listSelectedData.push(tableRow);
              }
            }
          });
        }
        // 全选取消
        else {
          this.tableData.forEach((tableRow) => {
            // 是否存在已选择数据中
            let selectKey = this.listSelectedData.indexOf(tableRow);
            // 不存在已选中
            if (selectKey >= 0) {
              this.listSelectedData.remove(tableRow);
            }
          });
        }
      }

      this.$emit("selectData", this.listSelectedData);
      this.$emit("selected-update", this.listSelectedData);
    },

    // 自动选中设置的已选中行数据
    autoSelectRow() {
      if (
        Object.prototype.toString.call(this.value) == "[object Array]" &&
        this.value.length > 0 &&
        this.selectionProp != null
      ) {
        let selectedValue = this.value;

        this.$nextTick(() => {
          this.tableData.forEach((row) => {
            if (selectedValue.indexOf(row[this.selectionProp]) >= 0) {
              this.$refs.myTable.toggleRowSelection(row, true);
            }
          });
        });
      }
    },
  },
  // 监听数据
  watch: {
    value: {
      immediate: true,
      handler(newVal, oldVal) {
        if (!newVal || newVal.length == 0) {
          this.listSelectedData = [];
          return;
        }
        this.autoSelectRow();
      },
    },
    // 监听数据变化
    viewData: {
      immediate: true,
      deep: true,
      handler(newVal, oldVal) {
        // this.loading = false;
        this.tableData = newVal.Data || newVal.data ||newVal.Items || newVal || this.tableData;

        let { TotalCount, TotalPage } = newVal;

        this.pageData.TotalCount =
          Object.prototype.toString.call(TotalCount) !== "[object Undefined]"
            ? TotalCount
            : this.pageData.TotalCount;
        this.pageData.TotalPage =
          Object.prototype.toString.call(TotalPage) !== "[object Undefined]"
            ? TotalPage == 0
              ? 1
              : TotalPage
            : this.pageData.TotalPage;

        this.autoSelectRow();

        this.$nextTick(() => {
          this.$refs.myTable.doLayout();
        });
      },
    },
  },
};
</script>

<style>
.elTable {
  width: 100%;
  margin-top: 6px;
}

.el-table__body td {
  padding: 8px 0 !important;
}
</style>